<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class Overview {

    private $Db = false;
    private $QueryMonth = false;

    public function __construct($QueryMonth) {
        $this->Db = Db::get_instance();
        $this->QueryMonth = $QueryMonth;
    }

    // 获取产品库存|生产|销售总览数据
    public function getProductOverView() {
        $SQL = "SELECT
	product_model,
	product_code,
	gongyi,
	number,
	COALESCE((SELECT sum(fac_product_order.finish_number) FROM `fac_product_order` WHERE `fac_product_order`.product_id = `fac_product_mess`.product_id),0) AS mproduce,
	COALESCE((SELECT sum(fi.number * fi.unit_price) FROM `fac_consumer_order_item` fi RIGHT JOIN fac_consumer_order fo on fo.consumer_order_id = fi.consumer_order_id WHERE fi.product_id = `fac_product_mess`.product_id AND fo.`order_state` = '已完成'),0) AS msale,
	COALESCE((SELECT sum(fi.number) FROM `fac_consumer_order_item` fi RIGHT JOIN fac_consumer_order fo on fo.consumer_order_id = fi.consumer_order_id WHERE fi.product_id = `fac_product_mess`.product_id AND fo.`order_state` = '已完成'),0) AS msalec
FROM
	fac_product_mess
WHERE
	hidden = 'no' ORDER BY `msalec` DESC";
        return $this->Db->query($SQL);
    }

    // 获取每个车间的生产数据
    public function getDepartmentDatas() {
        include dirname(__FILE__) . '/../department.php';
        
        $department = new department();
        $Res = $department->department_view_all();

        foreach ($Res as &$r) {
            $r['list'] = $this->Db->query("SELECT
	pm.product_model,
	COALESCE (ds.finish_number, 0) as fins,
	COALESCE (ds.unfinish_number, 0) as unfins,
	COALESCE ((select sum(number) from fac_department_product_record pdc where pdc.department_id = ds.department_id and pdc.product_id =  ds.product_id),0) as mpd,
	COALESCE ((select sum(number) from fac_department_product_record pdc where pdc.department_id = ds.department_id and pdc.product_id =  ds.product_id),0) as dpd
FROM
	fac_product_mess pm
LEFT JOIN fac_department_storehouse ds ON ds.product_id = pm.product_id
AND ds.department_id = $r[department_id]
WHERE
	pm.hidden = 'no';");
        }
        return $Res;
    }

    /**
     * 
     * @param type $val
     * @param type $def
     * @return type
     */
    private function __default($val, $def) {
        return $val ? $val : $def;
    }

}
